package cn.com.anypay.manager.controller.sdk;

import cn.com.anypay.manager.common.response.ApiResponse;
import cn.com.anypay.manager.service.OssService;
import cn.com.anypay.manager.miaoma.sysossrecord.SysOssRecordService;
import cn.com.anypay.manager.miaoma.sysossrecord.SysOssRecordEntity;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/oss")
public class OssController {
    @Resource
    private OssService ossService;

    @Resource
    private SysOssRecordService sysOssRecordService;

    @GetMapping("/config")
    public ApiResponse<Map<String, Object>> getCurrentConfig(
            @RequestParam(required = false) String provider,
            @RequestParam(required = false) String storageType) {
        // 优先使用 provider 参数，如果没有则使用 storageType 参数
        String actualProvider = provider != null ? provider : storageType;

        if (actualProvider != null) {
            // 如果是 local 类型，直接返回空配置
            if ("local".equals(actualProvider)) {
                log.info("本地存储类型，返回空配置");
                return ApiResponse.success(null);
            }

            log.info("根据提供商获取OSS配置: {}", actualProvider);
            Map<String, Object> config = ossService.getConfigByProvider(actualProvider);
            return ApiResponse.success(config);
        } else {
            log.info("获取当前OSS配置");
            Map<String, Object> config = ossService.getCurrentConfig();
            return ApiResponse.success(config);
        }
    }

    @PostMapping("/switch")
    public ApiResponse<String> switchProvider(@RequestBody Map<String, Object> config) {
        log.info("开始切换OSS服务商，配置参数: {}", config);
        String result = ossService.switchProvider(config);
        log.info("切换OSS服务商成功: {}", result);
        return ApiResponse.success("切换OSS服务商成功", result);
    }

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ApiResponse<Map<String,Object>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "isPublic", defaultValue = "true") boolean isPublic,
            @RequestParam(value = "path", required = false) String path
    ) {
        if (file == null || file.isEmpty()) {
            return ApiResponse.fail("请选择要上传的文件");
        }

        log.info("开始上传文件: {}, 大小: {} bytes, 是否公开: {}",
            file.getOriginalFilename(), file.getSize(), isPublic);

        Map<String,Object> result = ossService.uploadFile(file, path, isPublic);

        // 记录上传文件信息到数据库
        try {
            log.info("开始保存文件上传记录到数据库...");
            SysOssRecordEntity ossRecord = new SysOssRecordEntity();
            ossRecord.setFileName(file.getOriginalFilename());
            ossRecord.setFilePath((String) result.get("path"));
            ossRecord.setFileUrl((String) result.get("url"));
            ossRecord.setFileSize(file.getSize());
            ossRecord.setFileType(file.getContentType());
            ossRecord.setStorageType(result.getOrDefault("storageType", "local").toString());
            ossRecord.setStatus(1); // 1表示上传成功

            log.info("准备保存的记录信息: fileName={}, filePath={}, fileUrl={}, fileSize={}, fileType={}, storageType={}, status={}",
                ossRecord.getFileName(), ossRecord.getFilePath(), ossRecord.getFileUrl(),
                ossRecord.getFileSize(), ossRecord.getFileType(), ossRecord.getStorageType(), ossRecord.getStatus());

            boolean saveResult = sysOssRecordService.save(ossRecord);
            log.info("数据库保存结果: {}, 记录ID: {}", saveResult, ossRecord.getId());

            if (saveResult) {
                log.info("文件上传记录已成功保存到数据库: {}, 记录ID: {}", file.getOriginalFilename(), ossRecord.getId());
            } else {
                log.error("文件上传记录保存失败，save方法返回false");
            }
        } catch (Exception e) {
            log.error("保存文件上传记录失败: {}", e.getMessage(), e);
            log.error("异常堆栈信息: ", e);
            // 不影响文件上传的成功返回，只记录错误日志
        }

        log.info("文件上传成功: {}, URL: {}", file.getOriginalFilename(), result.get("url"));
        return ApiResponse.success(result);
    }

    @PostMapping("delete/{path}")
    public ApiResponse<Map<String,Object>> deleteFile(@PathVariable String path) {
        if (path == null || path.trim().isEmpty()) {
            return ApiResponse.fail("文件路径不能为空");
        }

        // 将下划线转换回斜杠
        String decodedPath = path.replace('_', '/');

        Map<String, Object> result = ossService.deleteFile(decodedPath);
        return ApiResponse.success(result);
    }
}
